package database.QueryDB.DBConn;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;

public class EmbeddedDerbyConn {
	private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
	static String dbName = "E:\\Java\\Joy\\derby\\Derby_data\\firstdb";
	static String url = "jdbc:derby:" + dbName + ";create=true";

	public static Connection getConn() {
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	public void doIt() throws SQLException {
		Connection conn = null;
		Statement s = null;
		ResultSet rs = null;
		conn = getConn();

		DatabaseMetaData meta = conn.getMetaData();
		ResultSet res = meta.getTables(null, null, null, new String[] { "TABLE" });
		HashSet<String> set = new HashSet<String>();
		while (res.next()) {
			set.add(res.getString("TABLE_NAME"));

		}

		try {
			s = conn.createStatement();
			
			if (set.contains("FIRSTTABLE")) {
				System.out.println("表FIRSTTABLE已经存在!");
				s.executeUpdate("DROP TABLE firsttable");
				s.executeUpdate("create table firsttable(id varchar(20), name varchar(20))");
			} else {
				System.out.println("表FIRSTTABLE不存在,创建新表!");
				s.executeUpdate("create table firsttable(id varchar(20), name varchar(20))");
			}
			s.executeUpdate("insert into firsttable values('1', 'Jim')");
			rs = s.executeQuery("select * from firsttable");
			while (rs.next()) {
				System.out.println("id:"+rs.getString(1));
				System.out.println("name:"+rs.getString(2));
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		try {
			conn.close();
			conn = null;
			s.close();
			s = null;
			rs.close();
			rs = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws SQLException {
		EmbeddedDerbyConn t = new EmbeddedDerbyConn();
		t.doIt();
	}
}
